<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="modelForm"
      :before-close="beforeClose"
      :data="tableData"
      :option="tableOption"
      @on-load="onLoad"
      @row-save="handleMetadataSave"
      @row-update="handleMetadaUpdate"
      @refresh-change="onLoad"
      @search-change="searchChange"
    >
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button @click.stop="errorInfo(row)" icon="el-icon-edit" :size="size" :type="type">异常反馈</el-button>
        <el-button @click.stop="inDBReport(row)" icon="el-icon-delete" :size="size" :type="type">入库报告</el-button>
        <el-button @click.stop="inDB(row)" icon="el-icon-delete" :size="size" :type="type">一键入库</el-button>
        <el-button @click.stop="processingReport(row)" icon="el-icon-delete" :size="size" :type="type">进度跟踪</el-button>

        <!--<el-button @click="copyFormAdd" icon="el-icon-document-copy" :size="size" :type="type">复制</el-button>-->
      </template>
      <template slot="FILENAME" slot-scope="scope">
        {{scope.row.attributes.FILENAME}}
      </template>
      <template slot="FILETYPE" slot-scope="scope">
        {{scope.row.attributes.FILETYPE}}
      </template>
      <template slot="FILESTATUS" slot-scope="scope">
        {{scope.row.attributes.FILESTATUS}}
      </template>
      <template slot="FILEORG" slot-scope="scope">
        {{scope.row.attributes.FILEORG}}
      </template>
      <template slot="KEYWORDS" slot-scope="scope">
        {{scope.row.attributes.KEYWORDS}}
      </template>
      <template slot="INDUSTRYSECTOR" slot-scope="scope">
        {{scope.row.attributes.INDUSTRYSECTOR}}
      </template>
      <template slot="FILESECTOR" slot-scope="scope">
        {{scope.row.attributes.FILESECTOR}}
      </template>
      <template slot-scope="{row}" slot="templateForm">
        <div style="width: 41.5%;float: left">
          <el-select v-model="modelForm.templateData" placeholder="请选择">
            <el-option
              v-for="item in templates"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey">
            </el-option>
          </el-select>
        </div>
        <div style="width: 18%;float: left;margin-left:4%;">
          <el-button type="primary">查看模板</el-button>
        </div>
      </template>
      <template slot-scope="{row}" slot="relatedataForm">
        <avue-input-tree v-model="modelForm.modelId" placeholder="请选择元数据" type="tree" :props="props"
                         :dic="modelTreeData" @change="changeModel"></avue-input-tree>
        <!--<div style="width: 48%;float: left;">-->
        <!--<avue-input-tree v-model="modelForm.modelPackageId" placeholder="请选择模型包" type="tree" :props="props" :dic="modelPackageTreeData" @change="changePackage"></avue-input-tree>-->
        <!--</div>-->
        <!--<div style="width: 48%;float: left;margin-left:4%;">-->
        <!---->
        <!--</div>-->
      </template>
      <template slot-scope="{row}" slot="modelPackageIdForm">
        <div>
          <avue-crud
            ref="property"
            v-model="propertyForm"
            :data="propertyList"
            :option="propertyOption"
          >
            <template slot="property" slot-scope="scope">

              <div v-if="scope.row.typeName === 'string'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <avue-input v-model="scope.row.property" placeholder="请输入值"></avue-input>
              </div>
              <div v-if="scope.row.typeName === 'date'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <avue-date v-model="scope.row.property" type="datetime" format="yyyy年MM月dd日 hh:mm:ss"
                           value-format="timestamp" placeholder="请选择日期"></avue-date>
              </div>
              <div v-if="scope.row.typeName === 'int'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <el-input-number v-model="scope.row.property" ></el-input-number>
              </div>
              <div v-if="scope.row.typeName === 'float'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <el-input-number v-model="scope.row.property" :precision="2" :step="0.1"></el-input-number>
              </div>
              <div v-if="scope.row.typeName === 'boolean'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;">*</span>
                <avue-radio v-model="scope.row.property" :dic="dic"></avue-radio>
              </div>
            </template>
          </avue-crud>
        </div>

      </template>
    </avue-crud>
    <el-dialog append-to-body
               :visible.sync="logDialog"
               width="auto">
      <m-log :key="logId" :item="item" :source="source" :logId="logId" @ok="ok" @close="close"></m-log>
    </el-dialog>
    <el-dialog append-to-body
               title="入库报告"
               :visible.sync="inDBReportDialog"
               width="50%">
      <el-row :gutter="24">
        <el-col>
          <div class="collection-term">模板:</div>
          <div class="collection-detail">身份证模板</div>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col>
          <div class="collection-term">关联元数据:</div>
          <div class="collection-detail">证件信息表</div>
        </el-col>
      </el-row>
      <avue-crud :data="inDBList" :option="inDBOption"></avue-crud>
    </el-dialog>
    <el-dialog append-to-body
               title="文件数据入库"
               :visible.sync="inDBDialog"
               width="50%">
      <el-row :gutter="24">
        <el-col>
          <div class="collection-term">模板:</div>
          <div class="collection-detail">身份证模板</div>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col>
          <div class="collection-term">关联元数据:</div>
          <div class="collection-detail">证件信息表</div>
        </el-col>
      </el-row>
      <ProgressTracking></ProgressTracking>
    </el-dialog>
    <el-dialog append-to-body
               title="进度跟踪"
               :visible.sync="processDialog"
               width="50%">
      <ProgressTracking></ProgressTracking>
    </el-dialog>
  </basic-container>
</template>
<script>
  import {
    getModelDetail,
    getMetadataPackageList
  } from '@/api/metadata/model';
  import {
    getMetaDataList
  } from '@/api/metadata/metadata';
  import {getFileList} from '@/api/dataMaintenance/fileManage';
  import {getList} from '@/api/metadata/grade';
  import {getLabelTree} from '@/api/metadata/label';
  import {listLabeltype} from '@/api/metadata/labeltype';
  import {
    getMetadataDetail,
    saveMetadata,
    deleteMeta
  } from '@/api/metadata/metadata';
  import mLog from '../metadata/log';
  import ProgressTracking from './progressTracking'
  export default {
    components: { mLog, ProgressTracking },
    data() {
      return {
        processDialog: false,
        inDBReportDialog: false,
        inDBDialog: false,
        logDialog: false,
        item: {},
        source: 'list',
        logId: 285,
        page: {},
        currentDir: null,
        tableData: [],
        isEdit: false,
        propertyForm: {},
        propertyList: [],
        propertyOption: {
          editBtn: false,
          delBtn: false,
          header: false,
          menu: false,
          column: [
            {
              label:'属性名称',
              prop:'name',
            },
            {
              label:'类型',
              prop:'typeName',
              type:'select',
              dicData: []
            },
            {
              label:'描述',
              prop:'description',
              type: "textarea"
            },
            {
              label:'属性值',
              prop:'property',
            },
          ]
        },
        props: {
          label: "name",
          value: "id"
        },
        modelTreeData: [],
        modelPackageTreeData: [],
        tableOption: {
          addBtnText:'上传',
          //addBtn:false,
          editBtn:false,
          delBtn:false,
          // height: 'auto',
          // calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: false,
          //editBtn: false,
          //addBtn: false,
          // viewBtn: true,
          // delBtn: false,
          // menuWidth: 350,
          dialogClickModal: false,
          menuWidth: 180,
          column: [
            {
              label: '文件名称',
              prop: 'FILENAME',
              search: true,
              display: false
            },
            {
              label: '文件类型',
              prop: 'FILETYPE',
              display: false
            },
            {
              label: '入库状态',
              prop: 'FILESTATUS',
              search: true,
              display: false
            },
            {
              label: '提供部门',
              prop: 'FILEORG',
              search: true,
              display: false
            },
            {
              label: '关键字',
              prop: 'KEYWORDS',
              search: true,
              display: false
            },
            {
              label: '数据领域',
              prop: 'INDUSTRYSECTOR',
              search: true,
              display: false
            },
            {
              label: '所属行业',
              prop: 'FILESECTOR',
              search: true,
              display: false
            }
          ],
          group: [
            {
              label: '基础信息',
              prop: 'baseInfo',
              icon: 'el-icon-tickets',
              labelWidth:110,
              column: [
                {
                  label: '文件',
                  prop: 'imgUrl',
                  type: 'upload',
                  loadText: '文件上传中，请稍等',
                  span: 24,
                  propsHttp: {
                    res: 'data'
                  },
                  tip: '',
                  action: '/imgupload'
                },
                {
                  label: "模板",
                  prop: "template",
                  span: 24
                },
                {
                  label: "关联元数据",
                  prop: "relatedata",
                  span: 12
                },
              ]
            },
            {
              label: '元数据信息维护',
              prop: 'metaInfo',
              icon: 'el-icon-tickets',
              labelWidth:110,
              column: [
                {
                  label: "名称",
                  prop: "name",
                  rules: [{
                    required: true,
                    message: "请输入名称",
                    trigger: "blur"
                  }]
                },
                {
                  label: "代码",
                  prop: "code",
                  rules: [{
                    required: true,
                    message: "请输入代码",
                    trigger: "blur"
                  }],
                  editDisabled:true
                },
                {
                  label:'标签',
                  prop:'labels',
                  type:'tree',
                  multiple:true,
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label:'分级',
                  prop:'grade',
                  type:'tree',
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label:'分类',
                  prop:'classification',
                  type:'tree',
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label: "描述",
                  prop: "remark",
                  type: "textarea",
                  minRows: 2,
                  span: 24
                },
                {
                  label: '元模型',
                  prop: 'modelPackageId',
                  span:24
                }
              ]
            }
          ]
        },
        modelForm: {
          'modelId': '',
          'modelPackageId': '',
          'templateData': ''
        },
        templates: [],
        entityAttr: {
          'name': '',
          'owner': '',
          'description': ''
        },
        // 默认写死
        modelPackageId: '1399975916334526465',
        modelId: '1394528482744504321',
        currentCategoryId: '1402513162386722817',
        typeName: 'DATAFILE',
        entityFilters: null,
        inDBList: [],
        inDBOption:{
          header:false,
          menu:false,
          page:false,
          column:[
            {
              label:'文件名称',
              prop:'name'
            }, {
              label:'入库开始时间',
              prop:'start'
            },
            {
              label:'入库结束时间',
              prop:'end'
            }, {
              label:'耗时',
              prop:'time'
            },
            {
              label:'入库状态',
              prop:'status'
            }, {
              label:'操作人',
              prop:'operator'
            }
          ]
        }
      }
    },
    mounted() {
      this.getModelDetail(this.modelId);
      this.getGradeList();
      this.getLabelList();
      this.getClassfication();
      this.getAllPackageList();
    },
    methods: {
      ok () {},
      close () {
        this.logDialog = false
      },
      errorInfo() {
        this.logDialog = true;
      },
      inDBReport() {
        this.inDBReportDialog = true;
      },
      inDB () {
        this.inDBDialog = true;
      },
      processingReport() {
        this.processDialog = true;
      },
      changePackage() {

      },
      changeModel() {

      },
      getAllPackageList() {
        getMetadataPackageList('').then(res => {
          this.modelPackageTreeData = res.data.data.concat([]);
          //this.handleModelMap(this.modelPackageTreeData);
        });
      },
      onLoad() {
        this.getFileList();
      },
      handleNodeClick(data) {
        this.currentDir = data;
        this.onLoad();
      },
      searchChange(params, done) {
        console.log(params);
        this.entityFilters = null;
        let keys = Object.keys(params);
        if (keys.length === 0) {
          this.entityFilters = null;
        } else {
          this.entityFilters = {
            condition: 'AND',
            criterion: keys.map(item => {
              return {
                attributeName: item,
                operator: 'contains',
                attributeValue: params[item]
              }
            })
          }
        }
        this.getFileList();
        done();
      },
      getFileList() {
        let obj = {
          "excludeDeletedEntities": true,
          "includeSubClassifications": true,
          "includeSubTypes": true,
          "includeClassificationAttributes": true,
          "entityFilters": this.entityFilters,
          "tagFilters": null,
          "attributes": ["FILENAME", "FILEORG", "FILEPATH", "FILESECTOR", "FILESIZE", "FILESTATUS", "FILETYPE", "INDUSTRYSECTOR", "KEYWORDS", "OWNER"],
          "limit": 10,
          "offset": 0,
          "query": null,
          "typeName": "DATAFILE",
          "classification": null,
          "termName": "1402513162386722817"
        }
        getFileList(obj).then(res => {
          this.tableData = res['data']['data']['entities'];
        }).catch(
          this.tableData = []
        )
      },
      getModelDetail(id) {
        getModelDetail(id).then( res => {
          if(res['data']['code'] === 200) {
            if(res['data']['data']['source'] && res['data']['data']['source'] !== '') {
              let model = JSON.parse(res['data']['data']['source']);
              this.propertyList = model['attributeDefs'];
              this.propertyList.forEach( item => {
                if(item['typeName'] === 'date') {
                  item['property'] = new Date().getTime();
                }
              });
              if(this.isEdit) {
                this.propertyList.forEach(item => {
                  item['property'] = this.entityAttr[item['name']];
                });
              }
            }
          }

        });
      },
      getGradeList() {
        getList().then(res => {
          this.tableOption.group[1].column[3].dicData = res['data']['data']['records']
        });
      },
      getLabelList() {
        getLabelTree().then(res => {
          this.tableOption.group[1].column[2].dicData = this.translateTreeData(res['data']['children'] || [])
        });
      },
      translateTreeData(treeData){
        let newTreeData = [];
        treeData.forEach(
          item => {
            let el = {
              ...item.label
            }
            if(item.children && item.children.length){
              el['children'] = this.translateTreeData(item['children']);
            }
            newTreeData.push(el);
          }
        )
        return newTreeData;
      },
      getClassfication() {
        listLabeltype().then(res => {
          this.tableOption.group[1].column[4].dicData = res['data']['data']['records']
        });
      },
      handleMetadataSave(row,done,loading) {
        let attr = {
          'name':row['name'],
          'qualifiedName':row['code'],
          'description':row['remark']
        };
        let propertyMap = {};
        let isAllRequireHasValue = true;
        let tempName = '';
        this.propertyList.forEach(item => {
          propertyMap[item['name']] = item['property'];
          if(!item['isOptional'] && (item['property'] === undefined || item['property'] === '' || item['property'] === null )){
            isAllRequireHasValue = false;
            tempName = item['name'];
          }
        });
        if(!isAllRequireHasValue) {
          this.$message.error(`${tempName}属性值必填`);
          loading();
          return;
        }
        let obj = {
          'categoryId':this.currentCategoryId,
          "entity": {
            "entity": {
              "attributes": {
                ...attr,
                ...propertyMap
              },
              "guid": -1,
              "typeName": this.typeName,
              "customAttributes": {
                "grade": row['grade'],
                "modelPkgId":this.modelPackageId,
                "modelId":this.modelId,
                "classification":row['classification']
              },
              labels: this.modelForm.labels
            }
          }
        };
        saveMetadata(obj).then( res => {
          if(res['data']['code'] === 200) {
            done();
            this.getFileList();
          }
        }).catch( res => {
          loading();
        });

      },
      handleMetadaUpdate(row,index,done,loading) {
        let attr = {
          'name':row['name'],
          'qualifiedName':row['code'],
          'description':row['remark']
        };
        let propertyMap = {};
        let isAllRequireHasValue = true;
        let tempName = '';
        this.propertyList.forEach(item => {
          propertyMap[item['name']] = item['property'];
          if(!item['isOptional'] && (item['property'] === undefined || item['property'] === '' || item['property'] === null)){
            isAllRequireHasValue = false;
            tempName = item['name'];
          }
        });
        if(!isAllRequireHasValue) {
          this.$message.error(`${tempName}属性值必填`);
          loading();
          return;
        }
        let obj = {
          'categoryId':this.currentCategoryId,
          "entity": {
            "entity": {
              "attributes": {
                ...attr,
                ...propertyMap
              },
              "guid": row['guid'],
              "typeName": row['typeName'],
              "customAttributes": {
                "grade": row['grade'],
                "modelPkgId":this.modelPackageId,
                "modelId":this.modelId,
                "classification":row['classification']
              },
              labels: this.modelForm.labels
            }
          }
        };
        saveMetadata(obj).then( res => {
          if(res['data']['code'] === 200) {
            done();
            this.getFileList();
          }
        }).catch( res => {
          loading();
        });
      },
      beforeClose(done) {
        let _t = this;
        _t.propertyList = [];
        _t.modelForm.name = '';
        _t.modelForm.code = '';
        _t.modelForm.remark = '';
        // _t.modelForm.modelId = '';
        // _t.modelForm.modelPackageId = '';
        _t.modelForm.classification = '';
        _t.modelForm.grade = '';
        _t.modelForm.labels = [];
        _t.isEdit = false;
        //this.$refs.crud.resetFields();
        done();
      },
    }
  }
</script>
<style lang="scss">
  .collection-term,.collection-detail {
    display: table-cell;
    padding-right: 10px;
    line-height: 20px;
    white-space: nowrap;
  }
</style>
